const FormData = require("form-data");
const fs = require("fs");
const path = require("path");
const url = require("url");
const buffer = require("buffer");
const _common = require("../_common");


let upload_url = "https://livere.me/v1/image/upload/";
let parsed = url.parse(upload_url);
let headers = {
  // host: "mp.toutiao.com",
  // origin: "https://mp.toutiao.com",
  // referer: "https://mp.toutiao.com/profile_v3/weitoutiao",
  // "user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36 OPR/51.0.2830.55",
  // cookie: `G_ENABLED_IDPS=google; disqus_unique=1r57ont17r0dn1; hubspotutk=034af80efda52e2d85cb852c1a10ea3d; sessionid=80904c58-37dd-11e8-8e78-002590f2e4a6; disqusauth="1|disqus_3Rdyy4Xbwh|0|0|0||281434844|//a.disquscdn.com/1524759628/images/noavatar32.png|0"; disqusauths="1525247556 98b51c78b4ab70fd5652f8817efc8adf2a82285dbc6b18ca0540f810b4051350"; __hstc=40641725.034af80efda52e2d85cb852c1a10ea3d.1516018992778.1516018992778.1525247559465.2; __hssrc=1; _ga=GA1.2.121579531.1525247555; _gid=GA1.2.531736709.1525247570; __utma=40641725.121579531.1525247555.1525247664.1525247664.1; __utmc=40641725; __utmz=40641725.1525247664.1.1.utmcsr=blog.cloudno.de|utmccn=(referral)|utmcmd=referral|utmcct=/blog/2018/03/18/introducing-devshell-ssh-access/; btIdentify=df33b6f6-08b2-41c7-bb49-b3d93966909e; _bti=%7B%22app_id%22%3A%22disqus%22%2C%22bsin%22%3A%22I1oik2h4cP6Rpl8EgQ8NdxJEuHmDSG5F6PZERmbpvjdsqQBP0NVPVKGN8sBWBZ%2FXCPaDghcORT6rIaaS4NQxVg%3D%3D%22%2C%22user_id%22%3A%220d84da506ed38b934e6caeaffd06443f1a62fdca2c2a3664d02cb8c9494a5045db84c55e1451b0279da8d1e4bcd4058b474bf6cdf8746c03dd1c6a3ca32f4be2%22%7D`
}


/**
 * 
 * @param {String} picture_path 图片完整路径,确定是有效路径 
 * @returns {Promise<{ok:Boolean,msg:String,picture_url:String}>}
 */
function upload(picture_path) {
  return new Promise(async resolve => {
    let o_getsize = await _common.getFileSize(picture_path);
    if (!o_getsize.ok) {
      return resolve({ ok: false, msg: `getFileSize failed : ${o_getsize.msg}`, picture_url: "" })
    }
    if (o_getsize.size >= 10 * 1024 * 1024) {
      return resolve({ ok: false, msg: `file size >= 10MB`, picture_url: "" })
    }
    let file_stream = fs.createReadStream(picture_path);
    let form = new FormData();
    form.append("lv_file", file_stream, {
      filename: path.basename(picture_path)
    });
    form.submit({
      host: parsed.host,
      path: parsed.path,
      protocol: parsed.protocol,
      headers: headers,
    }, (err, res) => {
      if (err) {
        return resolve({
          ok: false,
          msg: `Form submit failed : ${err.message}`
        })
      }
      if (res.statusCode != 200) {
        return resolve({
          ok: false,
          msg: `HTTP ${res.statusCode} ${res.statusMessage} `
        })
      }

      let buf = new buffer.Buffer("");
      res.on("data", (chunk) => {
        buf += chunk;
      });
      res.on("end", () => {
        let json = JSON.parse(buf);
        let picture_url = json[0]['image'];
        let parsed = url.parse(picture_url);
        let file_name = (() => {
          return parsed.pathname.replace("/s3.livere.com/", "");
          //from https://s3-ap-northeast-1.amazonaws.com/s3.livere.com/201852/10226-1146d64.PNG
          //like 201852/10226-1146d64.PNG
        })();
        let cloudfront_url = `https://d47jbcq60tnr6.cloudfront.net/${file_name}`
        resolve({
          ok:true,
          msg:"ok",
          picture_url:cloudfront_url
        })
      });
    })
  })
}

if(!module.parent){
  upload(path.join(__dirname,"../../tmp/tsdm.txt"))
}


module.exports = {
  upload:upload
}